﻿using ManagementApi.Models;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Microsoft.Extensions.Caching.Memory;
using Modules;
using Modules.Device;
using Modules.Device.Entitys;
using Modules.Device.Repositories;
using Newtonsoft.Json;
using Org.BouncyCastle.Ocsp;
using PmSoft;
using PmSoft.Exceptions;
using PmSoft.FileStorage;

namespace ManagementApi.Services
{
    /// <summary>
    /// 身份证阅读器相关服务
    /// </summary>
    [UseDI(ServiceLifetime.Scoped)]
    public class CardReaderService
    {
        private const string encKey = "!#$Ab0213UJ8235477JjuU&&";
        private readonly CardReaderDeviceService deviceService;
        private readonly CardReadRecordv2Repository cardReaderV2Repository;
        private readonly ManagementApplicationContext applicationContext;
        private readonly IMemoryCache memoryCache;
        private readonly IFileStorage fileStorage;
        private readonly ILogger logger;

        public CardReaderService(CardReaderDeviceService deviceService, IFileStorage fileStorage, IMemoryCache memoryCache, CardReadRecordv2Repository cardReaderV2Repository, ManagementApplicationContext applicationContext, ILogger<CardReaderService> logger)
        {
            this.deviceService = deviceService;
            this.memoryCache = memoryCache;
            this.cardReaderV2Repository = cardReaderV2Repository;
            this.applicationContext = applicationContext;
            this.fileStorage = fileStorage;
            this.logger = logger;
        }

        /// <summary>
        /// 获取身份读卡读取信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public CardInfo GetCardInfo(string token)
        {
            string decToken = ReaderEncrypt.Decrypt(token, isHex: true);
            if (string.IsNullOrEmpty(decToken))
                throw new BusinessException("签名解析错误");

            var parms = decToken.Split(',');

            //2023-12-01 暂时注释
            //if (parms.Length != 2)
            //    throw new BusinessException("签名错误");

            string readId = parms[0];
            //string   corpCode = parms[1];

            var report = memoryCache.Get<ReadCardReport>(decToken);
            if (report == null)
                throw new BusinessException($"身份证信息丢失，请重新读取");
            //var readerEntity = await cardReaderRepository.GetReaderEntityAsync(corpCode, report.SamId);
            //if (readerEntity == null)
            //	throw new BusinessException($"企业阅读器信息丢失");

            //var record = new CardReadRecord { CorpCode = corpCode, ReaderId = readerEntity.Id, OperationId = readId, OperationIp = applicationContext.ClientIp };
            //await cardReadRecordRepository.InsertAsync(record);

            var readerEntity = deviceService.GetSysDeviceByDeviceCode(report.SamId);
            if (readerEntity == null)
                throw new BusinessException($"身份证读卡器信息丢失");

            var record = new CardReadRecord
            {
                DeviceCode = readerEntity.DeviceCode,
                //CorpCode = corpCode,
                OperationIp = applicationContext.ClientIp,
                DeviceInfo = report.DeviceInfo,
                Name = report.Name,
                Sex = report.Sex,
                Race = report.Race,
                Birth = report.Birth,
                Address = report.Address,
                CardId = report.ID,
                Company = report.Company,
                BeginDate = report.GetBeginDate(),
                EndDate = report.GetEndDate(),
                ReadTime = DateTime.Now
            };
            cardReaderV2Repository.Insert(record);
            var cardInfo = (CardInfo)report;
            cardInfo.HasDeviceInfo = record.HasDeviceInfo();
            return cardInfo;
        }

        /// <summary>
        /// 验证阅读
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public void CheckReadAsync(string data)
        {
            try
            {
                // logger.LogInformation($"Service接收身份证阅读器传过来的参数:{data}");
                if (string.IsNullOrEmpty(data))
                    throw new BusinessException("报告数据不能为空");

                string decData = ReaderEncrypt.Decrypt(data, false, encKey);
                if (string.IsNullOrEmpty(decData))//解密失败，返回版本不一致，前端提示下载界面
                    throw new BusinessException("版本不一致");

                // logger.LogInformation($"Service接收身份证阅读器传过来的参数解析版:{decData}");

                var report = JsonConvert.DeserializeObject<ReadCardReport>(decData);
                if (report == null)
                    throw new ArgumentNullException(nameof(report));

                string decToken = ReaderEncrypt.Decrypt(report.Token, isHex: true);
                var parms = decToken.Split(',');
                if (parms.Length != 2)
                    throw new BusinessException("签名错误");
                string readId = parms[0];
                string corpCode = parms[1];

                var deviceEntity = deviceService.GetSysDeviceByDeviceCode(report.SamId);
                if (deviceEntity == null)
                {
                    deviceEntity = new CardReader { CorpCode = corpCode, DeviceCode = report.SamId, DeviceInfo = report.DeviceInfo, Description = report.Description, Status = 设备审核状态.已审核, CreateTime = DateTime.Now };
                    deviceService.CreateSysDevice(deviceEntity);
                }
                //2023-11-30暂时注释
                if (deviceEntity.Status == 设备审核状态.已审核 && string.IsNullOrEmpty(deviceEntity.CorpCode))
                {
                    deviceEntity.CorpCode = corpCode;
                    deviceService.UpdateSysDevice(deviceEntity);
                }
                //if (!string.IsNullOrEmpty(corpCode) && deviceEntity.CorpCode != corpCode)
                //    throw new BusinessException("该读卡器登记企业与当前企业不符");

                //if (!string.IsNullOrEmpty(corpCode) && deviceEntity.Status == 设备审核状态.已禁用)
                //    throw new BusinessException($"您使用的读卡器设备已被封禁，原因：{deviceEntity.DisableReason ?? "无"}");

                //if (!string.IsNullOrEmpty(corpCode) && deviceEntity.Status == 设备审核状态.待审核)
                //    throw new BusinessException("身份证读卡器信息未登记");

                if (!string.IsNullOrEmpty(report.Birth) && report.Birth.Length >= 8)
                {
                    string year = report.Birth.Substring(0, 4);
                    string month = report.Birth.Substring(4, 2);
                    string day = report.Birth.Substring(6, 2);
                    report.Birth = $"{year}-{month}-{day}";
                }
                memoryCache.Set(decToken, report, TimeSpan.FromMinutes(10));
            }
            catch (Exception ex)
            {
                logger.LogInformation($"程序出错：{ex.Message}");
                throw new BusinessException(ex.Message);
            }
        }
    }
}